package com.flyox.game.militarychess.client.multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

import com.flyox.game.militarychess.CONSTS;

public class BroadRecive {
	static BroadRecive ins=null;
	
	static MulticastSocket socket=null;
	static InetAddress group =null;
	private BroadRecive(){
	}
	public static BroadRecive getInstance(){
		//init
		try {
			group = InetAddress.getByName(CONSTS.SYS_CFG_BROAD_GROUP);// 声明建立组播组使用的组播组地址
			socket = new MulticastSocket(CONSTS.SYS_CFG_BROAD_PORT); // 初始化MulticastSocket类并将端口号与之关联
			socket.joinGroup(group);
			if(ins==null){
				ins=new BroadRecive();
			}
			return ins;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String getServerMsg(){ // 从组播组接收数据的函数
		String message = "";
		try {
			byte[] sendMsg="hello".getBytes();
			DatagramPacket packet = new DatagramPacket(sendMsg, sendMsg.length, group, CONSTS.SYS_CFG_BROAD_PORT);
			socket.send(packet);
			
			//recive message
			byte[] recData=new byte[15];
			packet = new DatagramPacket(recData, recData.length, group, CONSTS.SYS_CFG_BROAD_PORT);
			socket.receive(packet); // 通过MulticastSocket实例端口从组播组接收数据
			//message = new String(packet.getData(), 0, packet.getLength()).trim(); // 将接受的数据转换成字符串形式
			
			socket.setSoTimeout(5000);
			socket.receive(packet); // 通过MulticastSocket实例端口从组播组接收数据
			message = new String(packet.getData(), 0, packet.getLength()).trim(); // 将接受的数据转换成字符串形式
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return message;
	}
}
